//token验证中间件
import {NextFunction, Request, Response} from "express";
import httpStatusCodes from "@src/declarations/major/HttpStatusCodes";
import {getDecryptToken} from "@src/util/util";

// 验证token中间件
const verifyToken = (req: Request, res: Response, next: NextFunction) => {
  if (req.url === "/login") {
    return next();
  }
  const token = req?.headers?.token;
  const tokenErr = {
    msg: "未通过token验证",
    code: httpStatusCodes.UNAUTHORIZED,
  };
  if (!token) {
    res.json({data: tokenErr});
  } else {
    // token解密
    const tokenInfo = getDecryptToken(token as string);
    // token认证成功
    if (tokenInfo.token) {
      next();
    } else {
      // token过期
      tokenErr.msg = "token过期";
      res.json({data: tokenErr});
    }
  }
};

export default verifyToken;